package com.amtf.datafile3.core.std;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amtf.datafile3.DataCatalog;
import com.amtf.datafile3.DataException;
import com.amtf.datafile3.DataTable;
import com.amtf.datafile3.DataTableDefinition;

public abstract class AbsDataCatalog implements DataCatalog {

	protected String name = "";
	private final Map<String, DataTable> dataTables = new HashMap<String, DataTable>();

	public AbsDataCatalog(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getDataTableCount() {
		return dataTables.size();
	}

	public List<DataTable> getDataTables() {
		List<DataTable> tbs = new ArrayList<DataTable>();
		tbs.addAll(dataTables.values());
		return tbs;
	}

	public DataTable getDataTable(int index) {
		return getDataTables().get(index);
	}

	public void setDataTable(String name, DataTable tableSet) {
		dataTables.put(name.toUpperCase(), tableSet);
	}

	public boolean isDataTableExists(String name) {
		return dataTables.get(name.toUpperCase()) != null;
	}

	public DataTable getDataTable(String name) {
		return dataTables.get(name.toUpperCase());
	}

	public DataTable dropDataTable(String name) throws DataException {
		return dataTables.remove(name.toUpperCase());
	}

	public void setDataTableDefinition(DataTableDefinition definition) throws DataException {
		List<DataTable> list = this.getDataTables();
		for (DataTable dt : list) {
			dt.setDefinition(definition);
		}
	}

	public void setDataTableDefinition(String name, DataTableDefinition definition) throws DataException {
		DataTable dt = this.getDataTable(name.toUpperCase());
		if (dt != null) {
			dt.setDefinition(definition);
		}
	}

	public void close() {
		List<DataTable> list = this.getDataTables();
		for (DataTable dt : list) {
			dt.close();
		}
	}
}
